package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Sctmhistory;
import com.example.onlinemonitoring.model.Sctmsensor;
import com.example.onlinemonitoring.serviceImpl.SctmsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;

/**
 * 开关柜测温（许昌智能）
 */
@Service("sctmxjCom")
@Scope("prototype")
public class SctmxjCom extends CommPortManager {
    @Autowired
    private SctmsensorServiceImpl sctmserviceimpl;

    @Override
    public void receiveData(String str) {
        str = str.toUpperCase();
        setText(str);
        if (!CRC16.calcCrc16(str.substring(0, str.length() - 4))
                .equals(str.substring(str.length() - 4, str.length()))) {
            setText("CRC校验失败！数据格式不正确");
            return;
        }
        Integer pointaddr = 0;
        String addrstr = str.substring(0, 2);
        Integer addrint = parseHex4(addrstr);
        reSend[addrint] = 0;
        addrindex++;

        if (addrint <= 16) {
            pointaddr = addrint;
            addrint = 1;
        } else if (addrint <= 26) {
            pointaddr = addrint - 16;
            addrint = 2;
        } else if (addrint <= 61) {
            pointaddr = addrint - 26;
            addrint = 3;
        } else if (addrint <= 96) {
            pointaddr = addrint - 61;
            addrint = 4;
        } else if (addrint <= 131) {
            pointaddr = addrint - 96;
            addrint = 5;
        } else if (addrint <= 166) {
            pointaddr = addrint - 131;
            addrint = 6;
        } else if (addrint <= 174) {
            pointaddr = addrint - 166;
            addrint = 7;
        }
        Sctmsensor sctm = new Sctmsensor();
        sctm.setStationid(ad.getStationid());
        sctm.setDevicegroup(ad.getDevicegroup());
        sctm.setDeviceaddr(addrint);
        sctm.setPointaddr(pointaddr);
        sctm.setLastaupcontact(parseHex4(str.substring(6, 10)) * 1f);
        sctm.setLastbupcontact(parseHex4(str.substring(10, 14)) * 1f);
        sctm.setLastcupcontact(parseHex4(str.substring(14, 18)) * 1f);
        sctm.setLastalowcontact(parseHex4(str.substring(18, 22)) * 1f);
        sctm.setLastblowcontact(parseHex4(str.substring(22, 26)) * 1f);
        sctm.setLastclowcontact(parseHex4(str.substring(26, 30)) * 1f);

        Sctmsensor alarm = sctmserviceimpl.getModel(sctm);
        if (alarm == null) {
            setText("地址" + addrint + "监测点" + pointaddr + "不存在！");
            return;
        }
        sctm.setLastxjcommunicationstatus(0);
        sctm.setLastaupcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastaupcontact()),
                HexUtil.isnull(alarm.getAupcontactalarmvalue()),
                HexUtil.isnull(alarm.getAupcontactalarmrelievevalue()), HexUtil.isnull(alarm.getAupcontactwarnvalue()),
                HexUtil.isnull(alarm.getAupcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastaupcontactalarmstatus()), true, "上触头A相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));

        sctm.setLastbupcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastbupcontact()),
                HexUtil.isnull(alarm.getBupcontactalarmvalue()),
                HexUtil.isnull(alarm.getBupcontactalarmrelievevalue()), HexUtil.isnull(alarm.getBupcontactwarnvalue()),
                HexUtil.isnull(alarm.getBupcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastbupcontactalarmstatus()), true, "上触头B相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));

        sctm.setLastcupcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastcupcontact()),
                HexUtil.isnull(alarm.getCupcontactalarmvalue()),
                HexUtil.isnull(alarm.getCupcontactalarmrelievevalue()), HexUtil.isnull(alarm.getCupcontactwarnvalue()),
                HexUtil.isnull(alarm.getCupcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastcupcontactalarmstatus()), true, "上触头C相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));

        sctm.setLastalowcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastalowcontact()),
                HexUtil.isnull(alarm.getAlowcontactalarmvalue()),
                HexUtil.isnull(alarm.getAlowcontactalarmrelievevalue()),
                HexUtil.isnull(alarm.getAlowcontactwarnvalue()), HexUtil.isnull(alarm.getAlowcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastalowcontactalarmstatus()), true, "下触头A相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));

        sctm.setLastblowcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastblowcontact()),
                HexUtil.isnull(alarm.getBlowcontactalarmvalue()),
                HexUtil.isnull(alarm.getBlowcontactalarmrelievevalue()),
                HexUtil.isnull(alarm.getBlowcontactwarnvalue()), HexUtil.isnull(alarm.getBlowcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastblowcontactalarmstatus()), true, "下触头B相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));

        sctm.setLastclowcontactalarmstatus(GetAlarmStatus(HexUtil.isnull(sctm.getLastclowcontact()),
                HexUtil.isnull(alarm.getClowcontactalarmvalue()),
                HexUtil.isnull(alarm.getClowcontactalarmrelievevalue()),
                HexUtil.isnull(alarm.getClowcontactwarnvalue()), HexUtil.isnull(alarm.getClowcontactwarnrelievevalue()),
                HexUtil.isnull(alarm.getLastclowcontactalarmstatus()), true, "下触头C相温度", alarm.getDevicegroup(), addrint,
                alarm.getPointname(),
                pointaddr));
        sctm.setLastdatatimexj(new Date());
        String alarmMessage = "";
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastaupcontactalarmstatus()), "上触头A相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastbupcontactalarmstatus()), "上触头B相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastcupcontactalarmstatus()), "上触头C相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastalowcontactalarmstatus()), "下触头A相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastblowcontactalarmstatus()), "下触头B相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastclowcontactalarmstatus()), "下触头C相温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastacablealarmstatus()), "A相电缆温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastbcablealarmstatus()), "B相电缆温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastccablealarmstatus()), "C相电缆温度");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastbatteryvoltage7alarmstatus()), "A相电缆电池电压");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastbatteryvoltage8alarmstatus()), "B相电缆电池电压");
        alarmMessage += GetAlarmMessage(isnull(alarm.getLastbatteryvoltage9alarmstatus()), "C相电缆电池电压");
        sctm.setLastalarmlevel(HexUtil.MAX(new int[] { isnull(alarm.getLastaupcontactalarmstatus()),
                isnull(alarm.getLastbupcontactalarmstatus()), isnull(alarm.getLastcupcontactalarmstatus()),
                isnull(alarm.getLastalowcontactalarmstatus()), isnull(alarm.getLastblowcontactalarmstatus()),
                isnull(alarm.getLastclowcontactalarmstatus()), isnull(alarm.getLastacablealarmstatus()),
                isnull(alarm.getLastbcablealarmstatus()), isnull(alarm.getLastccablealarmstatus()),
                isnull(alarm.getLastbatteryvoltage7alarmstatus()), isnull(alarm.getLastbatteryvoltage8alarmstatus()),
                isnull(alarm.getLastbatteryvoltage9alarmstatus()) }));
        sctm.setLastalarmmessage(alarmMessage);
        sctm.setLastcommunicationstatus(HexUtil.MAX(
                new int[] { nto(alarm.getLastxjcommunicationstatus()), nto(alarm.getLastxycommunicationstatus()) }));
        sctm.setLasthisdatatimexj(addHistory(sctmserviceimpl.getModel(sctm)));
        sctmserviceimpl.Update(sctm, false);
    }

    private Date addHistory(Sctmsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatimexj() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatimexj()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Sctmsensor sensor) {
        Sctmhistory his = new Sctmhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setPointaddr(sensor.getPointaddr());
        his.setAddrname(sensor.getAddrname());
        his.setPointname(sensor.getPointname());
        his.setDatatime(sensor.getLastdatatime());
        his.setAupcontact(sensor.getLastaupcontact());
        his.setBupcontact(sensor.getLastbupcontact());
        his.setCupcontact(sensor.getLastcupcontact());
        his.setAlowcontact(sensor.getLastalowcontact());
        his.setBlowcontact(sensor.getLastblowcontact());
        his.setClowcontact(sensor.getLastclowcontact());
        his.setAcable(sensor.getLastacable());
        his.setBcable(sensor.getLastbcable());
        his.setCcable(sensor.getLastccable());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setAupcontactalarmstatus(sensor.getLastaupcontactalarmstatus());
        his.setBupcontactalarmstatus(sensor.getLastbupcontactalarmstatus());
        his.setCupcontactalarmstatus(sensor.getLastcupcontactalarmstatus());
        his.setAlowcontactalarmstatus(sensor.getLastalowcontactalarmstatus());
        his.setBlowcontactalarmstatus(sensor.getLastblowcontactalarmstatus());
        his.setClowcontactalarmstatus(sensor.getLastclowcontactalarmstatus());
        his.setAcablealarmstatus(sensor.getLastacablealarmstatus());
        his.setBcablealarmstatus(sensor.getLastbcablealarmstatus());
        his.setCcablealarmstatus(sensor.getLastccablealarmstatus());
        his.setAspare(sensor.getLastaspare());
        his.setBspare(sensor.getLastbspare());
        his.setCspare(sensor.getLastcspare());
        his.setMemo(sensor.getMemo());
        his.setInuse(sensor.getInuse());
        his.setStyle(sensor.getStyle());
        his.setAsparealarmstatus(sensor.getLastasparealarmstatus());
        his.setBsparealarmstatus(sensor.getLastbsparealarmstatus());
        his.setCsparealarmstatus(sensor.getLastcsparealarmstatus());
        his.setBatteryvoltage1(sensor.getLastbatteryvoltage1());
        his.setBatteryvoltage2(sensor.getLastbatteryvoltage2());
        his.setBatteryvoltage3(sensor.getLastbatteryvoltage3());
        his.setBatteryvoltage4(sensor.getLastbatteryvoltage4());
        his.setBatteryvoltage5(sensor.getLastbatteryvoltage5());
        his.setBatteryvoltage6(sensor.getLastbatteryvoltage6());
        his.setBatteryvoltage7(sensor.getLastbatteryvoltage7());
        his.setBatteryvoltage8(sensor.getLastbatteryvoltage8());
        his.setBatteryvoltage9(sensor.getLastbatteryvoltage9());
        his.setBatteryvoltage1alarmstatus(sensor.getLastbatteryvoltage1alarmstatus());
        his.setBatteryvoltage2alarmstatus(sensor.getLastbatteryvoltage2alarmstatus());
        his.setBatteryvoltage3alarmstatus(sensor.getLastbatteryvoltage3alarmstatus());
        his.setBatteryvoltage4alarmstatus(sensor.getLastbatteryvoltage4alarmstatus());
        his.setBatteryvoltage5alarmstatus(sensor.getLastbatteryvoltage5alarmstatus());
        his.setBatteryvoltage6alarmstatus(sensor.getLastbatteryvoltage6alarmstatus());
        his.setBatteryvoltage7alarmstatus(sensor.getLastbatteryvoltage7alarmstatus());
        his.setBatteryvoltage8alarmstatus(sensor.getLastbatteryvoltage8alarmstatus());
        his.setBatteryvoltage9alarmstatus(sensor.getLastbatteryvoltage9alarmstatus());
        sctmserviceimpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {

        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (isrun) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin()) {
                    addrindex = Appdevice.getAddrmin();
                }
                cstr = String.format("%s03", HexUtil.intToHexString(addrindex, 1));
                cstr += cmdtype;
                cstr += "0006";
                cstr += CRC16.calcCrc16(cstr);
                try {
                    Send(cstr);
                } catch (Exception EX) {
                    setText(EX.toString());
                }
                setText("向" + Appdevice.getName() + "（触头）设备发送采集" + nametype + "指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                    int pointaddr = 0;
                    int addrint = 0;
                    if (addrindex <= 16) {
                        pointaddr = addrindex;
                        addrint = 1;
                    } else if (addrindex <= 26) {
                        pointaddr = addrindex - 16;
                        addrint = 2;
                    } else if (addrindex <= 61) {
                        pointaddr = addrindex - 26;
                        addrint = 3;
                    } else if (addrindex <= 96) {
                        pointaddr = addrindex - 61;
                        addrint = 4;
                    } else if (addrindex <= 131) {
                        pointaddr = addrindex - 96;
                        addrint = 5;
                    } else if (addrindex <= 166) {
                        pointaddr = addrindex - 131;
                        addrint = 6;
                    } else if (addrindex <= 174) {
                        pointaddr = addrindex - 166;
                        addrint = 7;
                    }
                    Sctmsensor stcm = new Sctmsensor();
                    stcm.setDeviceaddr(addrint);
                    stcm.setDevicegroup(ad.getDevicegroup());
                    stcm.setStationid(ad.getStationid());
                    stcm.setPointaddr(pointaddr);
                    stcm.setLastxjcommunicationstatus(1);
                    if (sctmserviceimpl.Update(stcm, false) == 0) {
                        setText("数据更新失败！请检查原因...");
                    }
                    setText("设备端口通讯异常...请检查原因");
                    reSend[addrindex] = 0;
                    addrindex++;
                }
            } else if (rescode != 0) {
                setText(resmsg[rescode]);
            }
            Thread.sleep(timersp);
        }
    }
}
